#include "Triangle.h"
#include <iostream>
using namespace std;

Vector Triangle::getNormal (const Point& p) const
{
	Vector res = Vector(normal);
	res.normalize();
	return res;
}

Triangle::Triangle(const Point &_p1, const Point &_p2, const Point &_p3)
{
	p1 = _p1;
	p2 = _p2;
	p3 = _p3;
	normal = (Vector(p3, p1)^Vector(p2,p1));
}

bool Triangle::intersection(Ray& ray, Intersection& i) const
{
	Point P = ray.getOrigin();
	Vector V = ray.getDirection();
	double aire[3];
	double dist;
	bool val = false;

	double scalar = normal.scalar(V);
	
	if(scalar!=0)
	{
		dist = ( (normal.scalar(Vector(P, p1)))/ scalar);
		
		if(dist > 0.001)
		{
			Point pIntersection= ((ray.getDirection() * dist) + ray.getOrigin());

			aire[0] = normal.scalar((Vector(p1,pIntersection)^Vector(p2,pIntersection) ));
			aire[1] = normal.scalar((Vector(p2,pIntersection)^Vector(p3,pIntersection) ));
			aire[2] = normal.scalar((Vector(p3,pIntersection)^Vector(p1,pIntersection) ));
			
			if(((aire[0]>=0)&&(aire[1]>=0)&&(aire[2]>=0))||((aire[0]<=0)&&(aire[1]<=0)&&(aire[2]<=0)))
			{
				i.setC(color);
				Vector v = Vector(normal);
				v.normalize();
				i.setNormal(v);
				i.setP(pIntersection);
				i.setDistance(dist);
				return(true);
			}
		}
	}
	return(false);
}


